package com.ls.day7;

import java.util.Arrays;

public class ThreeSumClosest {
    public static void main(String[] args) {
        System.out.println(threeSumClosest(new int[]{-1,0,1,1,55},3));
    }

    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int min = 99999,sum=0;
        for (int i=0;i<nums.length;i++){
            if (i>0 && nums[i]==nums[i-1]) continue;

            int L=i+1,R=nums.length-1;

            while (L<R){
                int tmp = nums[i]+nums[L]+nums[R];
                if (tmp == target) return target;
                if(Math.abs(tmp-target)<min){
                    min = Math.abs(tmp-target);
                    sum = tmp;
                }

                if (tmp < target){
                    L++;
                }else R--;
            }
        }
        return sum;
    }
}
